package com.zzy.mccjt.model;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.zzy.mccjt.constant.RequestConstant;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * @program: mccjt-cloud
 * @description: 当前请求的来源系统
 * @author: zhouyang.zheng
 * @create: 2022-08-02 18:38
 **/
public class CurrentOriginSystem {

    public static final CurrentOriginSystem UNKNOWN_OS = new CurrentOriginSystem(RequestConstant.SYSTEM_UNKNOWN);

    private final String originSystem;

    private static final TransmittableThreadLocal<CurrentOriginSystem> CURRENT = new TransmittableThreadLocal<>();

    public static CurrentOriginSystem get() {
        final CurrentOriginSystem cos = CURRENT.get();
        if (cos == null || StringUtils.isEmpty(cos.originSystem)) {
            return UNKNOWN_OS;
        }
        return cos;
    }

    public static void set(String originSystem) {
        CURRENT.set(new CurrentOriginSystem(originSystem));
        MDC.put(RequestConstant.ORIGIN_SYSTEM, originSystem);
    }

    public static boolean isUnknown() {
        return RequestConstant.SYSTEM_UNKNOWN.equals(get().originSystem);
    }

    public static boolean isEmpty() {
        return CURRENT.get() == null;
    }

    public static void clear() {
        CURRENT.remove();
        MDC.remove(RequestConstant.ORIGIN_SYSTEM);
    }

    private CurrentOriginSystem(String originSystem) {
        this.originSystem = originSystem;
    }

    @Override
    public String toString() {
        return this.originSystem;
    }
}
